package org.chuan.auth.controller;

import org.chuan.auth.context.LoginContext;
import org.chuan.auth.dto.LoginDto;
import org.chuan.base.utils.AjaxResult;
import org.chuan.org.domain.Employee;
import org.chuan.org.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/login")
public class AuthController {

    @Autowired
    private IEmployeeService employeeService;

    @PostMapping
    public AjaxResult login(@RequestBody LoginDto loginDto){
        Employee employee = employeeService.queryByUsername(loginDto.getUsername());
        if (employee != null) {
            if (employee.getPassword().equals(loginDto.getPassword())) {
                // 登录成功
                // 生成 token【唯一不重复】
                String token = UUID.randomUUID().toString();
                // password做脱敏处理
                employee.setPassword("");
                // 往全局 Map里存放数据
                LoginContext.context.put(token,employee);
                // 组装返回到前端的数据
                Map<String,Object> map = new HashMap<>();
                map.put("token",token);
                map.put("user",employee);
                return AjaxResult.me().setData(map);
            } else {
                // 密码错误
                return AjaxResult.me().setSuccess(false).setMessage("密码错误");
            }
        } else {
            // 用户不存在
            return AjaxResult.me().setSuccess(false).setMessage("用户不存在");
        }
    }

}
